<template>
  <div class="container p-6">
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules"
      label-width="120px"
      class="question-form"
    >
      <!-- 基本信息 -->
      <el-form-item label="题目类型" prop="quType" required>
        <el-select v-model="form.quType" placeholder="请选择" size="large">
          <el-option
            v-for="item in questionTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="归属题库" prop="repoId" required>
        <el-select
          v-model="form.repoId"
          placeholder="选择或搜索题库"
          filterable
          size="large"
        >
          <el-option
            v-for="item in repoList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="题目内容" prop="content" required>
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="5"
          placeholder="请输入题目内容"
          size="large"
        ></el-input>
      </el-form-item>

      <el-form-item label="试题图片">
        <el-upload
          class="image-uploader"
          action="#"
          :http-request="handleUpload"
          :show-file-list="false"
        >
          <img v-if="form.image" :src="form.image" class="uploaded-image" />
          <el-button v-else type="primary" size="large">点击上传</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="整题解析">
        <el-input
          v-model="form.analysis"
          type="textarea"
          :rows="5"
          placeholder="请输入题目解析"
          size="large"
        ></el-input>
      </el-form-item>

      <!-- 选项部分 -->
      <div v-if="form.quType === 1 || form.quType === 2 || form.quType === 3">
        <div class="options-header flex items-center justify-between mb-4">
          <h3 class="text-lg font-medium">答案选项</h3>
          <el-button
            v-if="form.quType !== 3"
            type="primary"
            @click="addOption"
            size="large"
            icon="Plus"
            >添加</el-button
          >
        </div>

        <el-table :data="form.options" border style="width: 100%">
          <el-table-column label="序号" width="160" align="center">
            <template #default="scope">
              <div class="flex justify-center">
                <el-checkbox
                  v-if="form.quType === 2"
                  :model-value="scope.row.isRight === 1"
                  @change="(val) => (scope.row.isRight = val ? 1 : 0)"
                  >{{ String.fromCharCode(65 + scope.$index) }}</el-checkbox
                >
                <el-radio
                  v-else-if="form.quType === 1"
                  :model-value="getCorrectOptionIndex()"
                  :label="scope.$index"
                  @change="() => setCorrectOption(scope.$index)"
                  >{{ String.fromCharCode(65 + scope.$index) }}</el-radio
                >
                <el-radio
                  v-else-if="form.quType === 3"
                  :model-value="scope.row.isRight === 1 ? 1 : 0"
                  :label="scope.$index === 0 ? 1 : 0"
                  @change="() => handleJudgementChange(scope.row)"
                  >{{ scope.$index === 0 ? '是' : '否' }}</el-radio
                >
              </div>
            </template>
          </el-table-column>

          <el-table-column label="选项内容" align="center">
            <template #default="scope">
              <el-input
                v-model="scope.row.content"
                placeholder="请输入选项内容"
                size="large"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column label="选项图片" width="150" align="center">
            <template #default="scope">
              <el-upload
                class="option-image-uploader"
                action="#"
                :http-request="(file) => handleOptionUpload(file, scope.row)"
                :show-file-list="false"
              >
                <img
                  v-if="scope.row.image"
                  :src="scope.row.image"
                  class="option-image"
                />
                <el-button v-else size="small">选择图片</el-button>
              </el-upload>
            </template>
          </el-table-column>

          <el-table-column
            v-if="form.quType !== 3"
            label="操作"
            width="80"
            align="center"
            fixed="right"
          >
            <template #default="scope">
              <el-button type="danger" link @click="removeOption(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <!-- 按钮区域 -->
    <div class="action-buttons mt-8 flex">
      <el-button type="primary" size="large" @click="handleSave"
        >保存</el-button
      >
      <el-button size="large" @click="handleCancel">返回</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getRepolist } from '@/api/teacher/question'
import {
  addQuestion,
  getQuestionDetail,
  updateQuestion,
} from '@/api/teacher/testquestions'
import { uploadImage } from '@/api/teacher/index'

const router = useRouter()
const route = useRoute()

// 题目类型
const questionTypeList = ref([
  { value: 1, label: '单选题' },
  { value: 2, label: '多选题' },
  { value: 3, label: '判断题' },
  { value: 4, label: '简答题' },
])

// 题库列表
const repoList = ref([])

// 表单数据
const form = reactive({
  quType: 1, // 默认单选题
  repoId: '',
  content: '',
  image: '',
  analysis: '',
  options: [],
})

// 表单验证规则
const rules = {
  quType: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
  repoId: [{ required: true, message: '请选择归属题库', trigger: 'change' }],
  content: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
}

const formRef = ref(null)

// 加载题库列表
const loadRepoList = async () => {
  try {
    const { data } = await getRepolist()
    repoList.value = data
  } catch (error) {
    console.error('获取题库列表失败:', error)
    ElMessage.error('获取题库列表失败')
  }
}

// 获取正确选项的索引（单选题用）
const getCorrectOptionIndex = () => {
  const index = form.options.findIndex((option) => option.isRight === 1)
  return index >= 0 ? index : -1
}

// 设置正确选项（单选题用）
const setCorrectOption = (index) => {
  form.options.forEach((option, i) => {
    option.isRight = i === index ? 1 : 0
  })
}

// 处理判断题选项变更
const handleJudgementChange = (row) => {
  form.options.forEach((option) => {
    option.isRight = option === row ? 1 : 0
  })
}

// 添加选项
const addOption = () => {
  form.options.push({
    content: '',
    image: '',
    isRight: 0,
  })
}

// 移除选项
const removeOption = (index) => {
  form.options.splice(index, 1)
}

// 处理试题图片上传
const handleUpload = async (fileInfo) => {
  // 检查文件是否存在
  if (!fileInfo || !fileInfo.file) {
    ElMessage.warning('请选择有效的图片文件')
    return
  }

  // 获取文件对象
  const file = fileInfo.file

  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.warning('请选择图片文件')
    return
  }

  // 临时方案：直接读取为Base64用于预览
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    form.image = reader.result
  }

  // 使用FormData对象处理文件上传
  const formData = new FormData()
  formData.append('file', file)

  // TODO: 发送文件到后端API
  // 以下是示例，实际使用时请替换为真实的API调用
  // const { data } = await uploadImage(formData)
  // form.image = data.url // 假设后端返回图片URL
}

// 处理选项图片上传
const handleOptionUpload = (fileInfo, option) => {
  // 检查文件是否存在
  if (!fileInfo || !fileInfo.file) {
    ElMessage.warning('请选择有效的图片文件')
    return
  }

  // 获取文件对象
  const file = fileInfo.file

  // 验证文件类型
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.warning('请选择图片文件')
    return
  }

  // 使用FormData对象处理文件上传
  const formData = new FormData()
  formData.append('file', file)

  // TODO: 发送文件到后端API
  // 以下是示例，实际使用时请替换为真实的API调用
  // const { data } = await uploadOption(formData)
  // option.image = data.url // 假设后端返回图片URL

  // 临时方案：直接读取为Base64用于预览
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    option.image = reader.result
  }
}

// 初始化选项
const initOptions = () => {
  form.options = []

  if (form.quType === 1 || form.quType === 2) {
    // 单选题或多选题：添加ABCD四个选项
    for (let i = 0; i < 4; i++) {
      form.options.push({
        content: '',
        image: '',
        isRight: 0,
      })
    }
  } else if (form.quType === 3) {
    // 判断题：固定"正确"和"错误"两个选项
    form.options = [
      { content: '正确', image: '', isRight: 0 },
      { content: '错误', image: '', isRight: 0 },
    ]
  }
}

// 保存表单
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 验证选项
    if (
      (form.quType === 1 || form.quType === 2 || form.quType === 3) &&
      !hasCorrectAnswer()
    ) {
      ElMessage.warning('请至少选择一个正确答案')
      return
    }

    // 获取URL中的id参数，判断是新增还是编辑模式
    const id = route.query.id
    let result

    if (id) {
      // 编辑模式，调用更新API
      form.id = id // 确保ID正确传递给后端
      result = await updateQuestion(id, form)
    } else {
      // 新增模式，调用添加API
      result = await addQuestion(form)
    }

    const { code, msg } = result
    if (code == 1) {
      ElMessage.success('保存成功')
      router.push('/teacher/testquestions')
    } else {
      ElMessage.error(msg || '保存失败')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('保存失败，请检查表单')
  }
}

// 检查是否有正确答案
const hasCorrectAnswer = () => {
  return form.options.some((option) => option.isRight === 1)
}

// 返回
const handleCancel = () => {
  router.push('/teacher/testquestions')
}

// 组件挂载时执行
onMounted(async () => {
  // 首先加载题库列表
  await loadRepoList()

  // 获取URL中的id参数，判断是新增还是编辑模式
  const id = route.query.id
  if (id) {
    // 编辑模式，获取题目详情，不触发 watch
    await fetchQuestionDetail(id)
  } else {
    // 新增模式，初始化选项
    initOptions()
  }
})

// 获取题目详情
const fetchQuestionDetail = async (id) => {
  try {
    const { code, data } = await getQuestionDetail(id)
    if (code === 1 && data) {

      // 暂存题目类型，避免 watch 触发
      const oldQuType = form.quType

      // 填充表单数据（不触发 watch）
      Object.assign(form, {
        quType: data.quType,
        repoId: data.repoId,
        content: data.content,
        image: data.image || '',
        analysis: data.analysis || '',
        // 先清空选项，稍后再填充，避免触发 watch
        options: [],
      })

      // 填充选项数据
      if (data.options && data.options.length > 0) {
        // 排序选项，确保按sort字段顺序显示
        const sortedOptions = [...data.options].sort((a, b) => a.sort - b.sort)

        form.options = sortedOptions.map((option) => ({
          id: option.id,
          quId: option.quId,
          content: option.content || '',
          image: option.image || '',
          // 确保isRight字段是数值类型
          isRight:
            typeof option.isRight === 'boolean'
              ? option.isRight
                ? 1
                : 0
              : option.isRight === 1
              ? 1
              : 0,
          sort: option.sort || 0,
          isDeleted: option.isDeleted || 0,
        }))

      } else {
        // 若没有选项数据，则根据类型初始化
        if (form.quType === 1 || form.quType === 2) {
          // 单选题或多选题：添加ABCD四个选项
          for (let i = 0; i < 4; i++) {
            form.options.push({
              content: '',
              image: '',
              isRight: 0,
            })
          }
        } else if (form.quType === 3) {
          // 判断题：固定"正确"和"错误"两个选项
          form.options = [
            { content: '正确', image: '', isRight: 0 },
            { content: '错误', image: '', isRight: 0 },
          ]
        }
      }
    } else {
      ElMessage.error('获取题目详情失败')
      initOptions()
    }
  } catch (error) {
    console.error('获取题目详情失败:', error)
    ElMessage.error('获取题目详情失败')
    initOptions()
  }
}

// 监听题目类型变化，重新初始化选项
watch(
  () => form.quType,
  (newVal, oldVal) => {
    console.log(`题目类型变化: ${oldVal} -> ${newVal}, id:${route.query.id}`)

    // 获取URL中的id参数，判断是新增还是编辑模式
    const id = route.query.id

    // 如果是编辑模式的首次加载，不要重新初始化选项
    // 或者编辑模式下没有旧值(undefined)时，也不初始化
    if (id && (oldVal === undefined || form.options.length > 0)) {
      console.log('编辑模式，跳过选项初始化')
      return
    }

    initOptions()
  },
  { flush: 'post' } // 使用 post 模式，确保在 DOM 更新后触发
)
</script>

<style lang="less" scoped>
.container {
  background-color: white;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

.question-form {
  max-width: 900px;
  margin: 0 auto;
}

.options-header {
  padding: 10px 0;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  text-align: center;
  padding: 20px 0;
}

.uploaded-image {
  max-width: 100%;
  max-height: 300px;
}

.option-image {
  width: 80px;
  height: 50px;
  object-fit: cover;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

:deep(.el-table) {
  margin-bottom: 20px;

  .el-input {
    width: 100%;
  }

  .el-checkbox,
  .el-radio {
    margin-right: 0;
  }
}
</style>
